import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  info: null,
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  menus: [],
  stores: [],
  unitId: undefined,
  company: null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_INFO: (state, info) => {
    state.info = info
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_STORE: (state, company) => {
    state.company = company
    if (company) {
      state.unitId = company.id || undefined
    }
  },
  SET_STORES: (state, stores) => {
    state.stores = stores
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          // console.log(data)
          commit('SET_TOKEN', data.access_token)
          setToken(data.access_token, data.expired_at)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response

          if (!data) {
            reject('Verification failed, please Login again.')
          }

          const { roles, menus, stores, company, ...params } = data
          const { name, avatar, introduction } = params

          // console.log(roles, menus)

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!')
          }
          commit('SET_ROLES', roles)
          commit('SET_INFO', params)
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)
          commit('SET_MENUS', menus)
          commit('SET_STORE', company)
          commit('SET_STORES', stores)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_MENUS', [])
          commit('SET_STORE', [])
          removeToken()
          resetRouter()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_MENUS', [])
      removeToken()
      resolve()
    })
  },

  // remove token
  refreshToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_MENUS', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise((resolve, reject) => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      // const { roles, menus } = await dispatch('getInfo')

      dispatch('getInfo').then(res => {
        const { roles, menus } = res
        resetRouter()

        // generate accessible routes map based on roles
        dispatch('permission/generateRoutes', { roles, menus }, { root: true }).then(
          accessRoutes => {
            // dynamically add accessible routes
            router.addRoutes(accessRoutes)
          }
        )
        // const accessRoutes = await dispatch('permission/generateRoutes', { roles, menus }, { root: true })

        // dynamically add accessible routes
        // router.addRoutes(accessRoutes)

        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
